<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . './autoload.php';

// 运行在主进程
$ws_worker = new Worker("websocket://0.0.0.0:2347");

$ws_worker->count = 4;

$Client = [];

// 赋值过程运行在主进程
$ws_worker->onMessage = function(TcpConnection $connection, $data)use($ws_worker)
{
    global $Client;

    //保存用户登陆信息
    $ip    = $connection->getRemoteIp();
    $port  = $connection->getRemotePort();

    //Json化用户发来的消息
    $userMsg = json_decode($data,true);
    $loginName = $userMsg['from'];

    if($userMsg['model']=='Login'){
        //没有此用户就保存到列表
        if(!array_key_exists($loginName,$Client)){
            $Client[$loginName] = [$loginName,'ipp'=>$ip.':'.$port,'conn'=>$connection];//
            $datas = [
                'model'=>'connect',
                'from'=>$loginName,
                'toUid'=>$loginName,
                'msg'=>$loginName.'连接服务器成功'
            ];
            //只给当前用户发连接成功的消息
            //$connection->send(json_encode($datas));
            //print_r($Client[$loginName]);

            //给所有用户发连接成功的消息
            foreach ($ws_worker->connections as $connection){
                $connection->send(json_encode($datas));
            }
        }
    }elseif($userMsg['model']=='getList'){
            //给所有用户发用户列表消息
            $user = ['model'=>'getList','list'=>[]];
            foreach ($Client as $key){
                array_push($user['list'],$key[0]);
            }

            //var_dump($user);

          //给所有用户发连接成功的消息
            foreach ($ws_worker->connections as $connection){
                $connection->send(json_encode($user));
            }

    }else{
        //不是登陆，就转发消息
        if($userMsg['toUid']=='all'){
            //广播
            echo  "正在广播\r\n";
            echo "\r\n";

            foreach ($ws_worker->connections as $connection)
            {
                $datas = [
                    'model'=>'chat',
                    'from'=>$loginName,
                    'toUid'=>'all',
                    'msg'=>$userMsg['msg']
                ];
                $connection->send(json_encode($datas));
            }
        }else{
            //转发给私人
            echo "正在私聊给=>{$userMsg['toUid']}\r\n";
            echo "\r\n";
            $datas = [
                'model' =>'chat',
                'from'  =>$loginName,
                'toUid' =>$userMsg['toUid'],
                'msg'   =>$userMsg['msg']
            ];

            $Client[$userMsg['toUid']]['conn']->send(json_encode($datas));
        }


    }
    
};

Worker::runAll();

